<template>
    <div class="data-management-page">
      <!-- 数据筛选栏 -->
      <div class="data-filter-section">
        <div class="filter-header">
          <span class="section-title">数据筛选</span>
          <div class="filter-buttons">
            <el-button type="primary" @click="searchData">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </div>
        </div>
  
        <el-form :model="filterForm" class="filter-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="调拨单号">
                <el-input
                  v-model="filterForm.transferNo"
                  placeholder="请输入调拨单号"
                  clearable
                />
              </el-form-item>
            </el-col>
  
            <el-col :span="6">
              <el-form-item label="起始时间">
                <el-date-picker
                  v-model="filterForm.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-form-item>
            </el-col>
  
            <el-col :span="6">
              <el-form-item label="单据状态">
                <el-select
                  v-model="filterForm.status"
                  placeholder="请选择"
                  clearable
                >
                  <el-option label="待审核" value="pending" />
                  <el-option label="审核通过" value="approved" />
                  <el-option label="审核失败" value="rejected" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
  
      <!-- 数据列表操作栏 -->
      <div class="data-list-action-bar">
        <span class="section-title">数据列表</span>
        <div class="action-buttons">
          <el-button @click="editTransfer">编辑</el-button>
          <el-button type="danger" @click="deleteTransfer">删除</el-button>
        </div>
      </div>
  
      <!-- 数据表格 -->
      <el-table
        :data="dataList"
        border
        class="data-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="调拨单号" prop="allocateNum" min-width="120" />
        <el-table-column
          label="产品名称"
          prop="pRelatuionshipName"
          min-width="120"
        />
        <el-table-column label="产品编码" prop="pRelatNumber" min-width="120" />
        <el-table-column label="批次" prop="batch" width="100" />
        <el-table-column label="规格" prop="pRelatuionshipGuige" width="120" />
        <el-table-column label="数量" prop="quantity" width="90" />
        <el-table-column label="原仓库" prop="warehouseId" width="120" />
        <el-table-column label="原库位" width="120">
          仓库3：默认正式库位
        </el-table-column>
        <el-table-column label="调拨仓库" prop="alllocation" width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="editRow(row)"
              :disabled="row.status !== 'pending'"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="deleteRow(row)"
              :disabled="row.status !== 'pending'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </template>
  <script setup lang="ts">
  import { ElMessageBox, ElTable, ElMessage } from "element-plus";
  import { reactive, onMounted, ref } from "vue";
  import axios from "axios";
  import { Plus } from "@element-plus/icons-vue";
  import { useRouter, useRoute } from "vue-router";
  import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
  // 选中的行
  // 修改选择处理逻辑（确保ID有效性）
  const selectedRows = ref<any[]>([]);
  const handleSelectionChange = (val: any[]) => {
    selectedRows.value = val;
  };
  // 数据列表
  const dataList = ref([]);
  const form1 = reactive({
    TotalCount: 0,
    PageCount: 0,
    PageSize: 5,
    PageIndex: 1,
  });
  onMounted(() => {
    searchProducts();
  });
  const searchProducts = () => {
    KongaUrl
      .get("/wangcong/api/Whouase/GetAIIp", {
        params: {
          PageSize: form1.PageSize,
          PageIndex: form1.PageIndex,
        },
      })
      .then((res) => {
        dataList.value = res.data.data.list;
        form1.TotalCount = res.data.data.totalCount;
        form1.PageCount = res.data.data.PageCount;
      })
      .catch((error) => {
        console.error("获取产品列表失败", error);
      });
  };
  // 优化后的删除方法
  const handleDelete = async (id: any, productNum: any = []) => {
    try {
      let ids = [];
      let stockNumbers = [];
  
      if (id === "批量删除") {
        // 批量删除逻辑
        if (selectedRows.value.length === 0) {
          ElMessage.warning("请至少选择一条记录");
          return;
        }
        ids = selectedRows.value.map((item) => item.productNewSellModelId);
        stockNumbers = selectedRows.value.map((item) => item.productNum);
  
        await ElMessageBox.confirm(
          `确定要删除${selectedRows.value.length}条记录？`,
          "警告",
          { type: "warning" }
        );
      } else {
        // 单条删除逻辑
        ids = [id];
        stockNumbers = productNum;
  
        await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
          type: "warning",
        });
      }
  
      // 统一请求处理
      const params = new URLSearchParams();
      params.append("Table", "ProductNewSellModel");
      params.append("TableId", "ProductNewSellModelId");
      ids.forEach((id) => params.append("Ids", id.toString()));
      stockNumbers.forEach((num) => params.append("ProductNum", num));
  
      const res = await KongaUrl.delete(
        "/wangcong1/api/WHouase/DelsSell",
        {
          params: params,
          paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
        }
      );
  
      if (res.data.code === 500) {
        ElMessage.success(res.data.message);
        if (id === "批量删除") {
          selectedRows.value = []; // 清空选择
        }
      } else {
        ElMessage.error(res.data.message);
      }
    } catch (error) {
      if (error !== "cancel") {
        // 忽略用户取消操作
        ElMessage.error(`操作失败: ${error.message}`);
      }
    }
  };
  // 响应式数据
  const filterForm = reactive({
    transferNo: "",
    startTime: "",
    status: "",
  });
  // 模拟API请求
  
  // 重置筛选
  const resetFilter = () => {
    Object.assign(filterForm, {
      transferNo: "",
      startTime: "",
      status: "",
    });
  };
  
  // 分页处理
  const handleSizeChange = (newSize) => {
    form1.PageSize = newSize;
    searchProducts();
  };
  const handleCurrentChange = (newPage) => {
    form1.PageIndex = newPage;
    searchProducts();
  };
  
  // 批量操作
  const editTransfer = () => {
    if (selectedRows.value.length !== 1) {
      ElMessage.warning("请选择一条记录进行编辑");
      return;
    }
    // 实际应跳转编辑页或打开弹窗
    ElMessage.info("编辑功能开发中");
  };
  
  const deleteTransfer = async () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning("请选择要删除的记录");
      return;
    }
  
    try {
      // 实际调用删除接口
      await new Promise((resolve) => setTimeout(resolve, 500));
      ElMessage.success("删除成功");
    } catch (error) {
      ElMessage.error("删除失败");
    }
  };
  </script>
  <style scoped>
  /* 基础容器样式 */
  .data-management-page {
    padding: 24px;
    background: #f8fafc;
    min-height: 100vh;
    box-sizing: border-box;
  }
  
  /* 筛选区域美化 */
  .data-filter-section {
    margin-bottom: 24px;
    padding: 20px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
    position: relative;
    padding-left: 12px;
  }
  
  .section-title::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background: #3b82f6;
    border-radius: 2px;
  }
  
  /* 表单元素美化 */
  .filter-form .el-form-item {
    margin-bottom: 0;
  }
  
  .filter-form .el-input__inner,
  .filter-form .el-select__wrapper {
    border-radius: 8px;
    transition: all 0.3s ease;
  }
  
  .filter-form .el-input__inner:focus,
  .filter-form .el-select__wrapper:hover {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }
  
  /* 按钮组美化 */
  .filter-buttons .el-button {
    padding: 10px 20px;
    border-radius: 8px;
    transition: all 0.3s ease;
  }
  
  .filter-buttons .el-button--primary {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    border: none;
  }
  
  .filter-buttons .el-button--primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2);
  }
  
  /* 操作栏样式 */
  .data-list-action-bar {
    margin: 24px 0;
    padding: 16px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  .action-buttons .el-button {
    border-radius: 8px;
    padding: 10px 16px;
    transition: all 0.2s ease;
  }
  
  .action-buttons .el-button--primary {
    background: linear-gradient(135deg, #10b981, #059669);
    border: none;
  }
  
  .action-buttons .el-button--danger {
    background: linear-gradient(135deg, #ef4444, #dc2626);
    border: none;
  }
  
  /* 表格美化 */
  .data-table {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
  
  .data-table >>> .el-table__header th {
    background: #f1f5f9;
    color: #64748b;
    font-weight: 600;
  }
  
  .data-table >>> .el-table__row {
    transition: background 0.3s ease;
  }
  
  .data-table >>> .el-table__row:hover {
    background: #f8fafc !important;
  }
  
  /* 状态标签美化 */
  .el-tag {
    border: none;
    font-weight: 500;
  }
  
  .el-tag--warning {
    background: #fef3c7;
    color: #d97706;
  }
  
  .el-tag--success {
    background: #dcfce7;
    color: #16a34a;
  }
  
  .el-tag--danger {
    background: #fee2e2;
    color: #dc2626;
  }
  
  /* 操作按钮样式 */
  .data-table >>> .cell .el-button {
    padding: 6px 10px;
    border-radius: 6px;
    transition: all 0.2s ease;
  }
  
  .data-table >>> .cell .el-button:hover {
    background: #f1f5f9;
    transform: translateY(-1px);
  }
  
  /* 分页组件美化 */
  .pagination-wrapper {
    margin-top: 24px;
    padding: 16px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .data-management-page {
      padding: 16px;
    }
  
    .data-filter-section,
    .data-list-action-bar {
      padding: 16px;
    }
  
    .filter-form .el-col {
      width: 100%;
      max-width: 100%;
      margin-bottom: 12px;
    }
  
    .action-buttons {
      flex-wrap: wrap;
      gap: 8px;
    }
  
    .data-table >>> .el-table__cell {
      padding: 12px 8px;
    }
  }
  </style>